import Vue from 'vue'
import axios from 'axios'
import { VueAxios } from './axios'
import Cookie from 'js-cookie'
import { refreshT } from '@/api/login'
// 创建 axios 实例
const service = axios.create({
  baseURL: 'https://huaduo.tuohongwl.com/api', // /api base_url
  timeout: 60000, // 请求超时时间
  headers: {

    'Authorization': '',
  },
})
const err = (error) => {
  return Promise.reject(error)
}

service.interceptors.request.use(config => {
  if (Cookie.get('token_')) {
    const token = Cookie.get('token_')
    if (token) {
      config.headers['Authorization'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
  }
  return config
}, err => {
  return err
})


// 是否正在刷新
let isRefreshing = false
// 存放拦截下来的接口
let requests = []
service.interceptors.response.use((response) => {
  //401时不会进入这里
  return response.data
}, error => {
  let errorData = error.response
  if (errorData.status == 401) {
    const config = error.config
    if (!isRefreshing) {
      isRefreshing = true
      return refreshT().then(res => {
        Cookie.set('token_',`Bearer `+res.access_token)
        config.headers['Authorization'] = `Bearer ` + res.access_token
        const  token  = `Bearer ` + res.access_token
        requests.forEach(cb => cb(token))
        requests = []
        config.url=config.url.replace(/^\/api/,'')
        console.log(config,'上')
        return service(config)
      }).catch(err => {
        store.dispatch('Logout')
      }).finally(() => {
        isRefreshing = false
      })
    } else {
      return new Promise((resolve) => {
        requests.push((token) => {
          config.url=config.url.replace(/^\/api/,'')
          console.log(config,'下')
          resolve(service(config))
        })
      })
    }
  }else if(errorData.status==422 ){
    if(error.response.data.errors){
      let err = error.response.data.errors
      for(let i in err ){
        error.response.data.message = err[i][0]
        break;
      }
    }
  }
  return Promise.reject(error.response)
})
const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}